/*
背景：使用QT实现Tcp协议的服务器和客户端
当客户端连接上服务器后，服务器发送字样“welcome”至客户端，客户端把接受到的内容显示在界面上。
*/

#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QTcpSocket>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , m_ptcpserver(new QTcpServer)
{
    ui->setupUi(this);

    init_network();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::init_network(){
    if(!m_ptcpserver->listen(QHostAddress("127.0.0.1"), 8099)){
        QMessageBox::information(this, "listen", "start listen failed...");
        exit(1);
    }

    QMessageBox::information(this, "server listen", "start listen success...");

    connect(m_ptcpserver, &QTcpServer::newConnection, this, &Widget::new_connection);

    return;
}

void Widget::new_connection(){

    QTcpSocket* ptcpsocket = m_ptcpserver->nextPendingConnection();
    ptcpsocket->write("welcome");

    QMessageBox::information(this, "connect", "new connect");

    return;
}
